package servlet;

import dao.Dao;
import domain.Administrators;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        Cookie c = new Cookie("JSESSIONID",session.getId());
        c.setMaxAge(60*60);
        response.addCookie(c);
        String login_requestURI = (String) session.getAttribute("login_requestURI");
        Dao dao = new Dao();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String verifycode = request.getParameter("verifycode");
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        if (login_requestURI.contains("user")) {
            if (!checkcode_server.equalsIgnoreCase(verifycode)) {
                request.setAttribute("message", "验证码输入有误");
                request.getRequestDispatcher("/userLogin.jsp").forward(request, response);
                return;
            }
            request.removeAttribute("CHECKCODE_SERVER");
            User user = dao.login_user(username, password);
            if (user != null) {
                session.setAttribute("user_login",user);
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            } else {
                request.setAttribute("message", "用户名或密码错误");
                request.getRequestDispatcher("/userLogin.jsp").forward(request, response);
            }
        } else if (!login_requestURI.contains("user")) {
            if (!checkcode_server.equalsIgnoreCase(verifycode)) {
                request.setAttribute("message", "验证码输入有误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            request.removeAttribute("CHECKCODE_SERVER");
            Administrators administrators = dao.login_administrators(username, password);
            if (administrators != null) {
                session.setAttribute("administrators_login",administrators);
                response.sendRedirect(request.getContextPath() + "/AdminIndex.jsp");
            } else {
                request.setAttribute("message", "用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
